/*
 * @file     g_exit.h
 * @brief    source file for setting exit
 *
 * Change Logs:
 * Date            Author             Version        Notes
 * 2022-02-25      wsy                V1.0.0         the first version
 */
#include "g_dac.h"
#include "g_sysctrl.h"

/*
vol: 0~7  音量(0最大)
*/
void G_DAC_Init(uint8_t volume,G_FunctionalState IntrState,uint16_t water_level, uint8_t sample_multiple)
{
    /*DAC clk init*/
    G_SYSCTRL_AHBPeriphClockCmd(SYSCTRL_AHBPeriph_DAC, ENABLE);
	uint32_t sysctrl_per3, fs_div;

	if (sample_multiple == 2) {//16K sample rate
		sysctrl_per3 = SYSCTRL_PER3_Div2;
		fs_div = 1500;
	}
	else if (sample_multiple == 4) {//32K sample rate
		sysctrl_per3 = SYSCTRL_PER3_Div2;
		fs_div = 750;
	}
	else if (sample_multiple == 6) {//48K sample rate
		sysctrl_per3 = SYSCTRL_PER3_Div2;
		fs_div = 500;
	}
	else {//default 8K sample rate
		sysctrl_per3 = SYSCTRL_PER3_Div4;
		fs_div = 1500;
	}
    G_SYSCTRL_PER3AdacClkCtrl(RC48M, sysctrl_per3);
    DAC_FS_DIV = fs_div;
    DAC_COEF_A = 0x12972;
    DAC_THRESHOLD_GAIN = 0x80;
    DAC_THRESHOLD_MAX = 0x100;
    DAC_VOX_WINDOW = 0x40;
    DAC_VOL_TEST = ((volume<<4)|0x0e);
    DAC_CTRL = 0x16;
    DAC_CTRL = 0x17;
    DAC_CTRL = 0x07;
    DAC_CAL_WINDOW = 2;
    if(IntrState == ENABLE)
    {
        DAC_DOEN |= 1;
        DAC_WATER_LEVEL = water_level;
    }
}

/*
cont_mode: 1: 循环播放
           0：单次播放
buf:       pcm data buf
len:       pcm data len
*/
void G_DAC_Out(uint8_t mode, uint8_t *buf, uint32_t len)
{
    DAC_DMA_SADDR = (uint32_t)buf;
    DAC_DMA_EADDR = ((uint32_t)buf + len -4) & (0xfffffC);
    if (0 == mode)
    {
        DAC_CTRL = 7;
        DAC_DOEN |= (1 << 8);
        DAC_DOEN &= ~(1 << 8);
        DAC_DMA_EN = 1;
        while (0 == (DAC_DOEN & (1 << 8)));
    }
    else
    {
        DAC_CTRL = 7 | (1 << 5);
        DAC_DMA_EN = 1;
    }
}
void G_DAC_Off(void)
{
    DAC_CTRL |= (1 << 4);
    DAC_CTRL = 0;
	DAC_DMA_EN = 0;
}
